Components.utils.import("resource://gre/modules/DbTerminal.jsm");
Components.utils.import("resource://gre/modules/k9mailDb.jsm");



window.addEventListener("close",removeListenEvent,false);
window.addEventListener("load",showHasFoundDevices,false);

var elBreakoff = null;
var elenableConnect = null;
var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
                        .getService(Components.interfaces.nsIPromptService);
          
function initListenEvent(){
    if(!elBreakoff){
        elBreakoff = document.getElementById("messagepaneboxwrapper");
        elBreakoff.addEventListener("mouseover", isClosebreakoff, false);
    }
    if(!elenableConnect){
        elenableConnect = document.getElementById("messagepaneboxwrapper");
        elenableConnect.addEventListener("mouseover", isdisenableConnectCurSel, false);
    }
}

function removeListenEvent(){

    //linkStopFun();
    
    if(elBreakoff){
        elBreakoff.removeEventListener("mouseover", isClosebreakoff, false);
        elBreakoff = null;
    }
    if(elenableConnect){
        elenableConnect.removeEventListener("mouseover", isdisenableConnectCurSel, false);
        elenableConnect = null;
    }
     checkCloseDevState();
     dDeviceSqlite.onClose();
}
/*linkstop*/
function linkStopFun()
{
    //alert(1111);
    var listBox = document.getElementById("thelist");
    var dn=null;
    for(i=0;i<listBox.getRowCount();i++)
    {
       //alert(listBox[].length);
       listItemObj=listBox.getItemAtIndex(i);
       var ds=listItemObj.childNodes[0].getAttribute("label");
       if(ds=="连接中")
       {
          dn=listItemObj.childNodes[1].getAttribute("label"); 
       }
   } 
    //alert(dn);
    if(dn==null)
    {
        return;
    }
    var selectedDeviceStatus;
    var locationStr;
    dDeviceSqlite.onLoad();
    
    var statement = dDeviceSqlite.dbConnection.createStatement("\
                  SELECT dHandleStatus,dLocation FROM td_device WHERE dName =:myVal");
    statement.params.myVal = dn;
    try {
        while(statement.executeStep()) {
            selectedDeviceStatus = statement.row.dHandleStatus;
            locationStr=statement.row.dLocation;
            
        }
    }
    finally {
        statement.reset();
    }
    if(jumpflag==null)
    {
    var gEN = Components.classes["@nfs.hlj/upnpservice;1"].createInstance(Components.interfaces.nsIUpnpService);    
    //var locationStr=window.arguments[0].location;    
    var httpHead = locationStr.split("/")[0];
    var ipAndPort = locationStr.split("/")[2];
    var serviceSubStr =httpHead+"\/\/"+ipAndPort+"/upnp/control/tvcontrol1";
    gEN.SendAction(serviceSubStr,"Offline","line","off"); 
    //alert(123456789);
    }else{    
       return; 
    } 
}


function isClosebreakoff(){
     var btnBreak = document.getElementById("device-breakoff");
     var list = document.getElementById('thelist');
     var elem_child = list.childNodes;
     for(var i=0;i<elem_child.length;i++){
         if("listitem" === elem_child[i].nodeName){
             btnBreak.setAttribute("disabled", "false");
         }else{
             btnBreak.setAttribute("disabled", "true");
         }
     }
}

function isdisenableConnectCurSel(){
     var btnConnect = document.getElementById("device-connect");
     var list = document.getElementById('thelist');
     var elem_child = list.childNodes;
     for(var i=0;i<elem_child.length;i++){
         if("listitem" === elem_child[i].nodeName){
             btnConnect.setAttribute("disabled", "false");
         }else{
             btnConnect.setAttribute("disabled", "true");
         }
     }
}

function addDeviceInfo(deviceInfo, statusVal, locationVal,nameVal, udnVal){
    deviceInfo.push({status:statusVal, location:locationVal,name:nameVal, UDN:udnVal, listID:"dev_0"});
}

function getDeviceInfos()
{
    if(dDeviceSqlite.initialized && dDeviceSqlite.dbStatus){
        var deviceInfo = [{status:0, name:"设备名", UDN:"设备描述码", listID:"dev_0"}];
        
        //addDeviceInfo(deviceInfo,0,"GALAXY Note 4","1111-2222-3333-11111111123456");
        //addDeviceInfo(deviceInfo,0,"iPhone 6 plus","1111-2222-3333-11111111223456");
        //addDeviceInfo(deviceInfo,0,"小米 4S","1111-2222-3333-11111111323456");
        //addDeviceInfo(deviceInfo,0,"HUAWEI 6 Plus","1111-2222-3333-11111111423456");
        
        var ListId = null;
        var statement = dDeviceSqlite.dbConnection.createStatement("\
                  SELECT dListId FROM td_device ORDER BY dListId DESC LIMIT 0,1");
       try{
            while(statement.executeStep()){
                ListId = statement.row.dListId;
            }
        }
        finally{
            statement.reset();
        }
        if(ListId>=0){
            ListId += 1;
        }else{
            ListId = 1;
        }
        for(var i =1;i<deviceInfo.length;i++){
            deviceInfo[i].listID = ListId++;
        }
        var statement = dDeviceSqlite.dbConnection.createStatement("\
                                   INSERT INTO td_device (dName,dLocation,dStatus, dUDN, dListId) \
                                   VALUES (:dName,:dLocation, :dStatus, :dUDN, :dListId)");
        var params = statement.newBindingParamsArray();
        for(var i=1;i<deviceInfo.length;i++){
            var bp = params.newBindingParams();
            bp.bindByName("dName",deviceInfo[i].name);
            bp.bindByName("dLocation",deviceInfo[i].location);
            bp.bindByName("dStatus",deviceInfo[i].status);
            bp.bindByName("dUDN",deviceInfo[i].UDN);
            bp.bindByName("dListId",deviceInfo[i].listID);
            params.addParams(bp);
        }
        statement.bindParameters(params);
        statement.executeAsync({handleCompletion:function(aReason){
                while(1){
                    if(aReason !==Components.interfaces.mozIStorageStatementCallback.REASON_FINISHED){
                        continue;
                    }else{
                        break;   
                    }
                }
        }});
        statement.finalize();
//        dDeviceSqlite.onClose();
    }else{
        dDeviceSqlite.onLoad();
        getDeviceInfos();
    }
    return true;
}

function getCurrentDBinfo(){
    var deviceInfo = [{id:0 ,status:0, handleStatus:0,name:"设备名", UDN:"设备描述码", listID:"dev_0"}];
    
//    while(dDeviceSqlite.initialized ===false || dDeviceSqlite.dbStatus===false){
//        dDeviceSqlite.onLoad(); 
//    }
    var statement = dDeviceSqlite.dbConnection.createStatement("SELECT * FROM td_device");
    try{
        while(statement.executeStep()){
            deviceInfo.push(
                    {id:statement.row.dId,
                     status:statement.row.dStatus, 
                     handleStatus:statement.row.dHandleStatus,
                     name:statement.row.dName, 
                     UDN:statement.row.dUDN, 
                     listID:"dev_"+statement.row.dListId});
        }
    }
    finally{
        statement.reset();
    }
//    dDeviceSqlite.onClose();
    return deviceInfo;
}

function showHasFoundDevices(){
    
     dDeviceSqlite.onLoad();
     createFindDeviceList(getCurrentDBinfo());
}
var linkedDevArr=[{onetabname:'tabName',listoneid:'idNum',devUDN:"udnValue"}];
function createFindDeviceList(deviceInfo)
{
    initListenEvent();
    var listBox = document.getElementById("thelist");
    
    for(var i=1;i<deviceInfo.length;i++){
        var newListItem = document.createElement("listitem");
        newListItem.setAttribute("id", deviceInfo[i].listID);
        var listcellS = document.createElement("listcell");
        var listcellD = document.createElement("listcell");
        listcellS.setAttribute("id", deviceInfo[i].listID+"_status");
        listcellD.setAttribute("id", deviceInfo[i].listID+"_name");
        if(0 === deviceInfo[i].status){
            listcellS.setAttribute("label","未连接");
        }else if (1 === deviceInfo[i].status){
            listcellS.setAttribute("label","连接中");
        }else if(2 === deviceInfo[i].status){
            listcellS.setAttribute("label","已连接");
            if(newListItem.getAttribute('onclick')===null||newListItem.getAttribute('onclick')==="")
            { 
              var tabname=deviceInfo[i].name;
              var devudn=deviceInfo[i].UDN;
              //alert("tabname="+tabname);
              var listid=deviceInfo[i].listID.split("_")[1];
              linkedDevArr.push({onetabname:tabname,listoneid: listid,devUDN:devudn});
              newListItem.ondblclick=function(){
                 //openLinkDevAccout(tabname,listid);
                 openLinkDevAccout(linkedDevArr);
                 };
  
            }
        }else{
            prompts.alert(null, "提示", "连接时出现错误...");//alert("连接时出现错误...");
            return;
        }
        var devn=deviceInfo[i].name;
        //alert(devn.length);
        if(devn.length<=16)
        {    
         listcellD.setAttribute("label", deviceInfo[i].name);
        }else
        {
            let head=devn.substr(0, 4);
            let start=devn.length-4;
            let tail=devn.substr(start, 3);
            var showname=head+"···"+tail;
            listcellD.setAttribute("label", showname);
        }
        newListItem.appendChild(listcellS);
        newListItem.appendChild(listcellD);
        
        listBox.appendChild(newListItem);
    }
}

function isStartSearchHandle(){
    var btn = document.getElementById("device-find");
    if("开启搜索" === btn.label){
        btn.label = "关闭搜索";
        showHasFoundDevices();
    }else{
        dDeviceSqlite.dbConnection.executeSimpleSQL("DROP TABLE td_device");
        dDeviceSqlite.dbConnection.executeSimpleSQL("CREATE TABLE IF NOT EXISTS td_device (\
                dId INTEGER PRIMARY KEY AUTOINCREMENT, dName CHAR(50) NOT NULL,dLocation TEXT NOT NULL, dUDN TEXT NOT NULL,\
                dStatus INTEGER DEFAULT 0, dHandleStatus INTEGER DEFAULT 0, dListId INTEGER)");
        dDeviceSqlite.dbConnection.executeSimpleSQL("DROP TABLE td_account");
        dDeviceSqlite.dbConnection.executeSimpleSQL("CREATE TABLE IF NOT EXISTS td_account (\
                                                aId INTEGER PRIMARY KEY AUTOINCREMENT,\
                                                aName CHAR(50) NOT NULL,aPwd CHAR(50) \
                                                NOT NULL, aXml TEXT NOT NULL,aServiceType INTEGER,\
                                                dId INTEGER NOT NULL,aLastStatus INTEGER DEFAULT 0,aLocalStatus INTEGER DEFAULT 0,\
                                                aRemoteStatus INTEGER DEFAULT 0,aControlType INTEGER DEFAULT 0)");
        var curTab = document.getElementsByTagName("tab");
        var curTabpanel = document.getElementsByTagName("tabpanel");
        if(curTab.length>1){
            if(curTabpanel.length>1){
                for(var i=curTab.length-1;i>0;i--){
                    curTab[i].parentNode.removeChild(curTab[i]);
                    curTabpanel[i].parentNode.removeChild(curTabpanel[i]);
                }
            }
        }
        btn.label = "开启搜索";
        deleteAllFindDeviceList();
    }
}

function createListHeader(listBox){
    var newListhead = document.createElement("listhead");
    var newlistheader = document.createElement("listheader");
    newlistheader.setAttribute("label", "状态");
    newlistheader.setAttribute("style", "text-align:center;");
    newListhead.appendChild(newlistheader);
    var newlistheader = document.createElement("listheader");
    newlistheader.setAttribute("label", "设备名");
    newlistheader.setAttribute("style", "text-align:center;");
    newListhead.appendChild(newlistheader);
    listBox.appendChild(newListhead);
    var newListcols = document.createElement("listcols");
    var newlistcol = document.createElement("listcol");
    newlistcol.setAttribute("flex", "1");
    newListcols.appendChild(newlistcol);
    var newlistcol = document.createElement("listcol");
    newlistcol.setAttribute("flex", "2");
    newListcols.appendChild(newlistcol);
    listBox.appendChild(newListcols);
}

function deleteAllFindDeviceList(){
    var listBox = document.getElementById("thelist");
    while(listBox.hasChildNodes()){
        listBox.removeChild(listBox.firstChild);
    }
    createListHeader(listBox);
}

function checkCloseDevState()
{
    //alert("adasdsa");
    var listBox = document.getElementById("thelist");
    
    for(i=0;i<listBox.getRowCount();i++)
    {
       //alert(listBox[].length);
       listItemObj=listBox.getItemAtIndex(i);
       //alert(listItemObj.childsNode[0].label);
       var dn=listItemObj.childNodes[1].getAttribute("label");
       if(listBox.hasChildNodes()&&listItemObj.childNodes[0].getAttribute("label")==="连接中")
       {
           var statement = dDeviceSqlite.dbConnection.createStatement("\
                  UPDATE td_device SET dHandleStatus = 0, dStatus = 0 where dName = :myVal");
           statement.params.myVal = dn;
           while(statement.executeStep()){
                       //statement.finalize();
                continue;
            };
       }
       
    }
    
}

function connectCurSelDevices(){
     var list = document.getElementById('thelist');
     var count = list.selectedCount;
     if(0 === count){
         prompts.alert(null, "提示", "请指定某个或某几个需要连接的设备 ......");//alert("请指定某个或某几个需要连接的设备 ......");
         return -1;
     }else{
         dDeviceSqlite.dbConnection.executeSimpleSQL("CREATE TABLE IF NOT EXISTS td_account (\
                                                aId INTEGER PRIMARY KEY AUTOINCREMENT,\
                                                aName CHAR(50) NOT NULL,aPwd CHAR(50) \
                                                NOT NULL, aXml TEXT NOT NULL,aServiceType INTEGER,\
                                                dId INTEGER NOT NULL,aLastStatus INTEGER DEFAULT 0,aLocalStatus INTEGER DEFAULT 0,\
                                                aRemoteStatus INTEGER DEFAULT 0,aControlType INTEGER DEFAULT 0)");
    var selectedDeviceInfo =  [{dId:0 , dName:"设备名", dListId:0, dUDN:"UDN"}];
//    var listBox = document.getElementById("thelist");
    var dn=null;
//    for(i=0;i<listBox.getRowCount();i++)
//    {
//       //alert(listBox[].length);
//       listItemObj=listBox.getItemAtIndex(i);
//       var ds=listItemObj.childNodes[0].getAttribute("label");
//       if(ds=="连接中")
//       {
//          var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
//                        .getService(Components.interfaces.nsIPromptService);
//          prompts.alert(null, "提示", "请先断开连接中的设备");
//          //alert("请先断开连接中的设备"); 
//          return;
//       }
//   } 
        
         while(count--){
            var item = list.selectedItems[0];
            var exam=item.childNodes[1];
            var cell0=item.childNodes[0];
            var valueexam=exam.getAttribute("label");
            var cell0V=cell0.getAttribute("label");
            //alert(valueexam);
            if(cell0V==="已连接")
            {
                return;
            }
            list.removeItemAt(list.getIndexOfItem(item));
            /*jinhai*/
           
            var paramter = item.id.split("_");
            var statement = dDeviceSqlite.dbConnection.createStatement("\
                  UPDATE td_device SET dHandleStatus = 1, dStatus = 1 where dName = :myVal");
            statement.params.myVal = valueexam;
            while(statement.executeStep()){
               
                continue;
            }
            statement = dDeviceSqlite.dbConnection.createStatement("\
                  SELECT dName,dId,dListId,dUDN FROM td_device where dName = :myVal");
            statement.params.myVal = valueexam;
            while(statement.executeStep()){
                if(!document.getElementById("device_tab_"+statement.row.dListId)){
                    selectedDeviceInfo.push({
                        dId:statement.row.dId, 
                        dName:statement.row.dName, 
                        dListId:statement.row.dListId,
                        dUDN:statement.row.dUDN
                    });
                }
            }
        }
        //gEN.deviceid = "uuid:Upnp-TVEmulator-1_0-1234567898881";
        //alert(gEN.deviceid);
        freshDevicesList();
        createNewTabbox(selectedDeviceInfo);
     }
}

function breakoffCurSelDevices(){
 
     var gEN = Components.classes["@nfs.hlj/upnpservice;1"].createInstance(Components.interfaces.nsIUpnpService);
     var list = document.getElementById('thelist');
     var count = list.selectedCount;
     if(0 === count){
      prompts.alert(null, "提示", "请在设备列表中选择要断开的设备");
      //alert("请在设备列表中选择要断开的设备");
      return -1;
     }else{
         while(count--){
            var item = list.selectedItems[0];
            var paramter = item.id.split("_");
            var devicen=item.childNodes[1].getAttribute("label");
            var devices=item.childNodes[0].getAttribute("label");
            //alert(devicen);
            if(devices=="未连接"||devices=="连接中")
            {
                //alert("设备尚未连接成功，请重新选择断开设备");
                prompts.alert(null, "提示", "设备尚未连接成功，请重新选择断开设备");
                return;
            }
            list.removeItemAt(list.getIndexOfItem(item));
            var statement = dDeviceSqlite.dbConnection.createStatement("\
                  UPDATE td_device SET dStatus = 0, dHandleStatus = 0 where dName = :myVal");
            statement.params.myVal =devicen;
            try{
                 while(statement.executeStep()){
                    //statement.finalize();
                    continue;
                }
            }
            finally{
                statement.reset();
            }
            var accparamter;
            var locationStr;
            var statement = dDeviceSqlite.dbConnection.createStatement("\
                  SELECT dId,dLocation FROM td_device WHERE dName = :myVal");
            statement.params.myVal =devicen;
            try{
                 while(statement.executeStep()){
                    //statement.finalize();
                    accparamter=statement.row.dId;
                    locationStr=statement.row.dLocation;
                }
            }
            finally{
                statement.reset();
            }    
            var statement = dDeviceSqlite.dbConnection.createStatement("\
                  DELETE FROM td_account WHERE dId = :myVal");
            statement.params.myVal = accparamter;
            try{
                 while(statement.executeStep()){
                    continue;
                }
            }
            finally{
                statement.reset();
            }
            
            /* 
             *更新设备通讯录状态信息 
             */
//          var statement = dDeviceSqlite.dbConnection.createStatement("\
//         SELECT dName FROM td_device where dId = :myVal");
//                  statement.params.myVal = paramter[1];
//                 
//        try {
//                 while (statement.executeStep()) {
//                       var deviceNS=statement.row.dName;
//                      }
//                   }
//                 
//        finally {
//                  statement.reset();
//                }              
      var statement = dDeviceSqlite.dbConnection.createStatement("UPDATE td_contact \
                           SET cStatus = :myVal1  where cDeviceName = :myVal");
      statement.params.myVal = devicen;
      statement.params.myVal1 = 3;
      try {
        while (statement.executeStep()) {
            continue;
        }
      }
    finally {
        statement.reset();
    }
            var curTab = document.getElementById("device_tab_"+paramter[1]);
            if(curTab!==null){
                curTab.parentNode.removeChild(curTab);
            }
            var curTabpanel = document.getElementById("device_tabpanel_"+paramter[1]);
            if(curTabpanel!==null){
                curTabpanel.parentNode.removeChild(curTabpanel);
            }
            var tabbox=document.getElementById("myTabList");
            var deviceTabpanels = document.getElementById("device_tabpanels");
            var fistTab = document.getElementById("device_tab_0");     
            tabbox.selectedTab=fistTab;      
            deviceTabpanels.setAttribute("selectedIndex",0);  
        }
        freshDevicesList();
     }
     
    var httpHead = locationStr.split("/")[0];
    var ipAndPort = locationStr.split("/")[2];
    var serviceSubStr =httpHead+"\/\/"+ipAndPort+"/upnp/control/tvcontrol1";
    gEN.SendAction(serviceSubStr,"Offline","line","off");
    
     var menuItem=window.arguments[1];
     var panelTree = window.arguments[0];
     var elem_child = panelTree.childNodes;
     //alert(elem_child.length);
     if(elem_child.length>3){
         for(var i=0;i<elem_child.length;i++){
            if("showDevicesPanelTree"=== elem_child[i].id){
                  elem_child[i].parentNode.removeChild(elem_child[i]);         
            }
         }
         menuItem.setAttribute("checked",true);
         createDevicesListToPanel();
     }
     if(window.opener)
     {    
       var accCP=window.opener.frames["accountCentralPane"];
        var labelV=accCP.document.getElementById('AccountCentralTitle');
        labelV.setAttribute("value","DFuse Mail - Terminal Mail");
      var displayDesk = window.opener.document.getElementById("displayDeck");
      displayDesk.setAttribute('selectedIndex','0');
     var coll=window.opener.document.getElementById("messagepaneboxwrapper");
     coll.setAttribute('collapsed',true);
     var qfbbar=window.opener.document.getElementById("qfb-show-filter-bar");
     var afbbox=window.opener.document.getElementById("quick-filter-bar");
     afbbox.setAttribute('collapsed',true);
     qfbbar.setAttribute('checked',false);
     qfbbar.setAttribute('disabled',true);
 }else{
     var accCP=window.frames["accountCentralPane"];
     var labelV=accCP.document.getElementById('AccountCentralTitle');
     labelV.setAttribute("value","DFuse Mail - Terminal Mail");
     var displayDesk = document.getElementById("displayDeck");
     displayDesk.setAttribute('selectedIndex','0');
     var coll=document.getElementById("messagepaneboxwrapper");
     coll.setAttribute('collapsed',true);
     var qfbbar=document.getElementById("qfb-show-filter-bar");
     var afbbox=document.getElementById("quick-filter-bar");
     afbbox.setAttribute('collapsed',true);
     qfbbar.setAttribute('checked',false);
     qfbbar.setAttribute('disabled',true);
 }
//     var menuItem = window.arguments[1];
//     alert(menuItem.getAttribute("checked"));
//     if(menuItem.getAttribute("checked")){
//         alert(1);
//         var panelTree = window.arguments[0];
//         var elem_child = panelTree.childNodes;
//         for(var i=0;i<elem_child.length;i++){
//            if("showDevicesPanelTree" === elem_child[i].id){
//                  elem_child[i].parentNode.removeChild(elem_child[i]);
//            }
//         }
//         alert(1);
//         createDevicesListToPanel();
//     }
}

function freshDevicesList(){
    /*
    var btn = document.getElementById("device-find");
    if("关闭搜索" !== btn.label){
        return -1;
    }
    */
    var deviceInfo = [{id:0 ,status:0,handleStatus:0, name:"设备名", UDN:"设备描述码", listID:"dev_0"}];
    while(dDeviceSqlite.initialized ===false || dDeviceSqlite.dbStatus===false){
        dDeviceSqlite.onLoad(); 
    }
    var statement = dDeviceSqlite.dbConnection.createStatement("SELECT * FROM td_device");
    try{
         while(statement.executeStep()){
            deviceInfo.push(
                    {id:statement.row.dId,
                     status:statement.row.dStatus, 
                     handleStatus:statement.row.dHandleStatus,
                     name:statement.row.dName, 
                     UDN:statement.row.dUDN, 
                     listID:"dev_"+statement.row.dListId});
         }
    }
    finally{
        statement.reset();
    }
//    dDeviceSqlite.onClose();
    deleteAllFindDeviceList();
    createFindDeviceList(deviceInfo);
}

/*
function closeDeviceListWindow(){
    removeListenEvent();
    window.close();
}
*/
var coltime=null;
function createNewTabbox(selectedDeviceInfo){
    var deviceTabs = document.getElementById("device_tabs");
    //deviceTabs.advanceSelectedTab(1,false);
    var deviceTabpanels = document.getElementById("device_tabpanels");
    var num=deviceTabpanels.childNodes.length;
    //alert(num);
    coltime =function(){
           
            var linkDevObj =devList.queryElementAt(num,uuid);
            checkDevAlidyResult(linkDevObj);
            
       }
    
    for(var i=1;i<2;i++){//selectedDeviceInfo.length
        var newTab = document.createElement("tab");
        newTab.setAttribute("id", "device_tab_"+selectedDeviceInfo[i].dListId);
        newTab.setAttribute("label", selectedDeviceInfo[i].dName);
        
        //newTab.setAttribute("selected",true);
        newTab.setAttribute("crop", "end");
        newTab.setAttribute("style", "width:80px");
        newTab.setAttribute("value", "device_tabpanel_"+selectedDeviceInfo[i].dListId);
        newTab.setAttribute("linkedpanel", "device_tabpanel_"+selectedDeviceInfo[i].dListId); 
        //deviceTabs.setAttribute("selectedIndex",num);
        deviceTabs.appendChild(newTab); 
        var tabbox=document.getElementById("myTabList");
        tabbox.selectedTab=newTab;
        var newTabpanel = document.createElement("tabpanel");
        newTabpanel.setAttribute("minheight","330");
        newTabpanel.setAttribute("manheight","330");
        newTabpanel.setAttribute("id","device_tabpanel_"+selectedDeviceInfo[i].dListId);
        newTabpanel.setAttribute("label",selectedDeviceInfo[i].dUDN);
        //tabbox.selectedPanel=newTabpanel;
        deviceTabpanels.setAttribute("selectedIndex",num);
        deviceTabpanels.appendChild(newTabpanel);
        
        
        //var newTab1 = document.getElementById("device_tab_"+selectedDeviceInfo[i].dListId);
        //newTab1.setAttribute("selected",true);
        var curUDN = selectedDeviceInfo[i].dUDN;
        var tarCode = curUDN.substr(curUDN.length-6,curUDN.length);
        var num=null; 
        var upnpServiceList =Components.classes["@nfs.hlj/upnpservice;1"].getService();
        var devList = upnpServiceList.getdevice();
        var uuid =  Components.ID("{5aaf3bbd-993e-4402-a1ea-73a1a07a6e4b}");
        
        for(var j=0;j < devList.length;j++)
        { 
            var device = devList.queryElementAt(j,uuid);
            if(curUDN === device.uuid)
            {
                upnpServiceList.deviceid=curUDN;
                num=j;
                break;
            }
        }
        setTimeout(coltime,100);   
        var linkDevObj =devList.queryElementAt(num,uuid);
        var locationStr=linkDevObj.location;
        var httpHead = locationStr.split("/")[0];
        var ipAndPort = locationStr.split("/")[2];
        var serviceSubStr=httpHead+"\/\/"+ipAndPort+"/upnp/event/tvcontrol1";
        upnpServiceList.connectDevice(serviceSubStr); 
    
    
        generationQRCode(newTabpanel.id, tarCode); 
       
       //alert(window[names]);
              
   }
    
     /*function(){
           
            var linkDevObj =devList.queryElementAt(num,uuid);
            checkDevAlidyResult(linkDevObj);
       }*/
}
    
  /*验证设备连接结果*/  
  var timeSwitchs=null;
   var jumpflag=null;
  function checkDevAlidyResult(dev)
 {
    var gEN = Components.classes["@nfs.hlj/upnpservice;1"].createInstance(Components.interfaces.nsIUpnpService);
    var linkresult=gEN.flag;
    if(linkresult=="success")//gEN.flag==="success"
    {
        clearTimeout(timeSwitchs);
        finishSelTabpanelContent(dev); 
        jumpflag="success";
        
    }else if(linkresult=="timeout")
    {  
        //alert(121);
        //
        linkdeverror(dev);
        jumpflag="fail";
        var statement = dDeviceSqlite.dbConnection.createStatement("\
                  UPDATE td_device SET dHandleStatus = 0, dStatus = 0 where dName = :myVal");
           statement.params.myVal = dev.name;
           while(statement.executeStep()){
                continue;
            };
        freshDevicesList();
        if(timeSwitchs)
        {    
          clearTimeout(timeSwitchs);
        }
    }
    else
    { 
        timeSwitchs=setTimeout(coltime,100);
    }    
 }
 /*重复连接一个设备*/

 function linkdeverror(dev)
 {
    var deviceTabs = document.getElementById("device_tabs");
    var elem_child = deviceTabs.childNodes; 
  //alert("xx");
         var curTabPanel = null;
         for(var i=0;i<elem_child.length;i++){
            if("tab" === elem_child[i].nodeName){
                if(true === elem_child[i].selected && "首页" !== elem_child[i].label){
                    //alert("elem_child.length ="+elem_child.length);
                    curTabPanel = document.getElementById(elem_child[i].value);
                }
            }
        }
        if(curTabPanel){
            var childs = curTabPanel.childNodes;
            for(var i=0;i<childs.length;i++){
                if("vbox" === childs[i].nodeName){
                    return;
                }
            }
            for(var i=childs.length-1;i>=0;i--){
                curTabPanel.removeChild(childs.item(i));
            }
        } 
        var vboxe=document.createElement("vbox");
        vboxe.setAttribute("align","center");
        var vcaption=document.createElement("caption");
        vcaption.setAttribute("label","注意：当前设备已有连接，请尝试重启设备UPNP服务");
        vcaption.setAttribute("style","color:red");
        vcaption.setAttribute("align","center");
        var vdescription=document.createElement("description");
        vdescription.setAttribute("align","center");
        var vimage=document.createElement("image");
        vimage.setAttribute("src","chrome://messenger/skin/icons/linkerrorimage.gif");
        vdescription.appendChild(vimage);
        var vSpacer = document.createElement("space");
        vSpacer.setAttribute("style", "height:30px");
        
         var vSpacer1 = document.createElement("space");
        vSpacer1.setAttribute("style", "height:50px");
        
        vboxe.appendChild(vSpacer1);
        vboxe.appendChild(vcaption);
        vboxe.appendChild(vSpacer);
//        <hbox flex="1">
//            
//            <button id="device-close" label="关闭" oncommand="removeListenEvent();"/>
//                       
//        </hbox>
        var vboxb=document.createElement("hbox");
        vboxb.setAttribute("align", "right");
        var cbutton=document.createElement("button");
        cbutton.setAttribute("label","关闭");
        cbutton.setAttribute("id","tab-close");
        cbutton.setAttribute("oncommand","closeCurTab();");
        var cl1=document.createElement("label");
        var cl2=document.createElement("label");
        vboxb.appendChild(cl1); 
        vboxb.appendChild(cl2); 
        vboxb.appendChild(cbutton); 
        vboxe.appendChild(vdescription);
        vboxe.appendChild(vSpacer);
        //vboxe.appendChild(vboxb); 
        curTabPanel.appendChild(vboxe);
        //curTabPanel.appendChild(vboxb);
 }
 function closeCurTab()
 {
      var deviceTabpanels = document.getElementById("device_tabpanels");
      var deviceTabs = document.getElementById("device_tabs");
      var elem_child = deviceTabs.childNodes; 
      var curTabPanel = null;
      for(var i=0;i<elem_child.length;i++){
            if("tab" === elem_child[i].nodeName){
                if(true === elem_child[i].selected && "首页" !== elem_child[i].label){
                    //alert("elem_child.length ="+elem_child.length);
                    curTabPanel = document.getElementById(elem_child[i].value);
                }
            }
        }
        if(curTabPanel){
            var childs = curTabPanel.childNodes;
            for(var i=childs.length-1;i>=0;i--){
                curTabPanel.removeChild(childs.item(i));
            }
        } 
        curTabPanel.parentNode.removeChild(curTabPanel);
      var tabbox=document.getElementById("myTabList");
 
      var curTab = tabbox.selectedTab;
            if(curTab!==null){
                curTab.parentNode.removeChild(curTab);
            }
      var fistTab = document.getElementById("device_tab_0");     
      tabbox.selectedTab=fistTab;      
      deviceTabpanels.setAttribute("selectedIndex",0);       
 }
 
/*获取连接成功设备内的邮箱账户信息*/
function getAccountsInfo(dev){
    var accountsInfo = [{aName: "账户名", aPwd: "用户密码",  aXml:"数据XML文件",aServiceType: "服务类型", dId: 0}];
    
    //var accountList=window.arguments[0].get();
     var accountList=dev.get();
     var auuid = Components.ID("{f5e32d2b-646a-4f2c-b011-d343dbc3bc60}");
     var Account = accountList.queryElementAt(0,auuid);
    //alert(Account.name);
    if(accountList !== null)
             {
               var auuid = Components.ID("{f5e32d2b-646a-4f2c-b011-d343dbc3bc60}");
               var al = accountList.length;
               //alert(al);
               for(var j = 0;j < accountList.length;j++)
               {
                   //alert(i);
                   var Account = accountList.queryElementAt(j,auuid);
                   var ANameS = Account.name;
                   var APwdS  = Account.password;
                   var AServiceS = Account.service;
                   var AXmlS=Account.accountid;
                   accountsInfo.push({aName: ANameS, aPwd: APwdS, aXml: AXmlS, aServiceType: AServiceS, dId: 0});
                   //alert("account name");
                   //alert(aname);
                }
            }
    
    //accountsInfo.push({aName: "zelei@nfs-hlj.com", aPwd: escape("密码测试"), aServiceType: "imap", dId: 0});
    //accountsInfo.push({aName: "525898211@qq.com", aPwd: escape("密码测试"), aServiceType: "pop3", dId: 0});
    //alert(accountsInfo.length);
    return accountsInfo;
}
/*test link success state*/
function gettestAccountsInfo(){
    var accountsInfo = [{aName: "账户名", aPwd: "用户密码", aServiceType: "服务类型", dId: 0}];
    accountsInfo.push({aName: "zelei@nfs-hlj.com", aPwd: escape("密码测试"), aXml: "73bc68c4-6616-495d-8b0e-33af0b430583.sqlite",aServiceType: "imap", dId: 0});
    accountsInfo.push({aName: "525898211@qq.com", aPwd: escape("密码测试"), aXml: "73bc68c4-6616-495d-8b0e-33af0b430583.sqlite",aServiceType: "pop3", dId: 0});
    return accountsInfo;
    
}

var linkDevDid=null;
function saveAccountsInfoToDB(tabpanelID,dev){
    var accounstInfo = getAccountsInfo(dev);
    //var accounstInfo= gettestAccountsInfo();
//    for(var i=0;i<accounstInfo.length;i++)
//    {
//        alert(accounstInfo[i].aName);
//    }
    var selectedDeviceID;
    var selectedTabPanelID = tabpanelID;
    var selectedDeviceListID = selectedTabPanelID.split("_")[2];
    //alert("selectedDeviceListID="+selectedDeviceListID);
    var statement = dDeviceSqlite.dbConnection.createStatement("\
                  SELECT dId FROM td_device where dUDN = :myVal");
    statement.params.myVal = dev.uuid;
    try{
         while(statement.executeStep()){
            selectedDeviceID = statement.row.dId;
        }
    }
    finally{
        statement.reset();
    }
    linkDevDid=selectedDeviceID;
    statement = dDeviceSqlite.dbConnection.createStatement("INSERT INTO \
                           td_account (aName, aPwd, aXml, dId, aServiceType) \
                           VALUES (:aName, :aPwd, :aXml,:dId, :aServiceType)");
    var params = statement.newBindingParamsArray();
    for(var i=1;i<accounstInfo.length;i++){
        var bp = params.newBindingParams();
        bp.bindByName("dId",selectedDeviceID);
        bp.bindByName("aPwd",accounstInfo[i].aPwd);
        bp.bindByName("aXml",accounstInfo[i].aXml);
        bp.bindByName("aName",accounstInfo[i].aName);
        bp.bindByName("aServiceType",accounstInfo[i].aServiceType);  
        params.addParams(bp);
    }
    statement.bindParameters(params);
    statement.executeAsync({handleCompletion:function(aReason){
            while(1){
                if(aReason !==Components.interfaces.mozIStorageStatementCallback.REASON_FINISHED){
                    continue;
                }else{
                    break;   
                }
            }
    }});
    statement.finalize();
}
/*
function saveAccountsInfoToDB(event){
    statement = dDeviceSqlite.dbConnection.createStatement("INSERT INTO \
                  td_account (aName, aPwd, dId, aServiceType, aStatus) \
                  VALUES (:aName, :aPwd, :dId, :aServiceType, :aStatus)");
    var params = statement.newBindingParamsArray();
    var selectedTabPanelID = event.rangeParent.id;
    for(var i=1;i<accounstInfo.length;i++){
        var bp = params.newBindingParams();
        bp.bindByName("dId",selectedDeviceID);
        bp.bindByName("aPwd",accounstInfo[i].aPwd);
        bp.bindByName("aName",accounstInfo[i].aName);
        bp.bindByName("aStatus",accounstInfo[i].aStatus);
        bp.bindByName("aServiceType",accounstInfo[i].aServiceType);  
        params.addParams(bp);
    }
}
*/
function removeTabPanelChildren(panelID){
    var pnode = document.getElementById(panelID);
    var childs = pnode.childNodes;
    for(var i=chlids.length-1;i>=0;i--){
        pnode.removeChild(childs.item(i));
    }
}


function processCreateAccountRequest(event){
    //alert("进入我");
    var selectedTabPanelID = event.target.parentNode.parentNode.parentNode.id;
   
     var tabptemp= event.target.parentNode.parentNode.parentNode;
     
     var selectedTalPanelUDN=tabptemp.getAttribute("label");
     //alert(selectedTalPanelUDN);
     var statement = dDeviceSqlite.dbConnection.createStatement("\
         SELECT dId FROM td_device where dUDN = :myVal");
                  statement.params.myVal = selectedTalPanelUDN;
                 
        try {
                 while (statement.executeStep()) {
                       var deviceId=statement.row.dId;
                      }
                   }
                 
        finally {
                  statement.reset();
                } 
    
    //var index = selectedTabPanelID.split("_")[2];
    //alert("indexaaa="+index);
    var index=deviceId;
    var statement = dDeviceSqlite.dbConnection.createStatement("\
                  SELECT aId FROM td_account where dId = :myVal");
    statement.params.myVal = deviceId;//index
    var checkBoxIndexArray = new Array();
    try{
         while(statement.executeStep()){
             checkBoxIndexArray.push(statement.row.aId);
        }
    }
    finally{
        statement.reset();
    }
    //alert(checkBoxIndexArray.length);
    var ckeckboxItem = new Array();
    var selectedCheckbox = new Array();
    for(var i=0;i<checkBoxIndexArray.length;i++){
        ckeckboxItem.push(document.getElementById("tab_panel_row_checkbox_"+index+"_"+checkBoxIndexArray[i]));
    }
    
    if(ckeckboxItem.length){
        var isCheckboxChecked = false;
        for(var i=0;i<ckeckboxItem.length;i++){
            if(ckeckboxItem[i].checked){
                isCheckboxChecked = true;
                selectedCheckbox.push(ckeckboxItem[i]);
            }
        }
        if(isCheckboxChecked){
           try{ 
                 //alert("获取通讯录信息");
            sentsgetContactsAction(selectedCheckbox[0].id);
            for (var i = 0; i < selectedCheckbox.length; i++) {
                //alert("selectedCheckbox.length="+selectedCheckbox.length);
                if (executeSelectStatus(selectedCheckbox[i].id)) {
                    continue;
                } else {
                    break;
                }
                //window.close();
            }
        }catch(e){
          alert(" out error");
//            for (var i = 0; i < selectedCheckbox.length; i++) {
//                //alert("selectedCheckbox.length="+selectedCheckbox.length);
//                if (executeSelectStatus(selectedCheckbox[i].id)) {
//                    continue;
//                } else {
//                    break;
//                }
//                //window.close();
//            }
            
        }
        
        }else{
            prompts.alert(null, "提示", "请选择需要创建的一个或几个账户....");
            //alert("请选择需要创建的一个或几个账户....");
        }
    }else{
        prompts.alert(null, "提示", "请选择需要创建的一个或几个账户...");
        //alert("请选择需要创建的一个或几个账户...");
    }    
}



function createCurTabPanel(panelID,dev){
    //alert("index=");
//    var index = panelID.split("_")[2];
//    alert("index="+index);
      var selectedDeviceID;
        var statement = dDeviceSqlite.dbConnection.createStatement("\
                  SELECT dId FROM td_device where dUDN = :myVal");
    statement.params.myVal = dev.uuid;
    try{
         while(statement.executeStep()){
             selectedDeviceID = statement.row.dId;
        }
    }
    finally{
        statement.reset();
    }
    var index=selectedDeviceID;
    var curTabpanel = document.getElementById(panelID);
    //alert("index2222="+index);
    var mainBox = document.createElement("vbox");
    mainBox.setAttribute("id","tabpanel_vbox_"+index);
    mainBox.setAttribute("flex","1");
    
    var tmpSpacer = document.createElement("spacer");
    tmpSpacer.setAttribute("style","height:15px");
    mainBox.appendChild(tmpSpacer);
    var headerBox = document.createElement("hbox");
    var tmpSpacer = document.createElement("spacer");
    tmpSpacer.setAttribute("style","width:25px");
    headerBox.appendChild(tmpSpacer);
    var strLabel = document.createElement("label");
    strLabel.setAttribute("value","当前设备内邮箱账户");
    headerBox.appendChild(strLabel);
    var tmpSpacer = document.createElement("spacer");
    tmpSpacer.setAttribute("style","width:50px");
    headerBox.appendChild(tmpSpacer);
    var strLabel = document.createElement("label");
    strLabel.setAttribute("value","服务类型");
    headerBox.appendChild(strLabel);
    var tmpSpacer = document.createElement("spacer");
    tmpSpacer.setAttribute("style","width:25px");
    headerBox.appendChild(tmpSpacer);
    var strLabel = document.createElement("label");
    strLabel.setAttribute("value","远程/本地管理");
    headerBox.appendChild(strLabel);
    mainBox.appendChild(headerBox);
    var mainGroupBox = document.createElement("groupbox");
    var tmpSpacer = document.createElement("spacer");
    tmpSpacer.setAttribute("style","height:15px");
    mainGroupBox.appendChild(tmpSpacer);
    var mainGrid = document.createElement("grid");
    mainGrid.setAttribute("maxheight","220px");
    mainGrid.setAttribute("minheight","220px");
    mainGrid.setAttribute("style","overflow:auto");
    var columnheader = document.createElement("columns");
    var column = document.createElement("column");
    column.setAttribute("flex", "3");
    columnheader.appendChild(column);
    var column = document.createElement("column");
    column.setAttribute("flex", "1");
    columnheader.appendChild(column);
    var column = document.createElement("column");
    column.setAttribute("flex", "1");
    columnheader.appendChild(column);
    var column = document.createElement("column");
    column.setAttribute("flex", "1");
    columnheader.appendChild(column);
    mainGrid.appendChild(columnheader);
    var rowheader = document.createElement("rows");
    var accountsInfo = [{aName:"账户名", 
                         aServiceType:"服务类型", 
                         aLocalStatus:"本地状态", 
                         aRemoteStatus:"远程状态",
                         aLastStatus:"最后状态",
                         aXml:"数据文件XML",
                         dId:0,
                         aId:0}];

    
    var statement = dDeviceSqlite.dbConnection.createStatement("\
                  SELECT * FROM td_account where dId = :myVal");
    statement.params.myVal = selectedDeviceID;
    try{
         while(statement.executeStep()){
             accountsInfo.push({
                 aName:statement.row.aName, 
                 aServiceType:statement.row.aServiceType, 
                 aLocalStatus:statement.row.aLocalStatus, 
                 aRemoteStatus:statement.row.aRemoteStatus, 
                 aLastStatus:statement.row.aLastStatus,
                 aXml:statement.row.aXml,
                 dId:statement.row.dId,
                 aId:statement.row.aId});
        }
    }
    finally{
        //statement.finalize();
        statement.reset();
    }
    //alert("index"+accountsInfo.length);
    for(var i=1;i<accountsInfo.length;i++){
        var newRow = document.createElement("row");
        newRow.setAttribute("id", "tab_panel_row_"+index+"_"+accountsInfo[i].dId);
        var checkbox = document.createElement("checkbox");
        checkbox.setAttribute("id", "tab_panel_row_checkbox_"+index+"_"+accountsInfo[i].aId);
        var strName = (accountsInfo[i].aName).split("@")[0];
        var strTempName = null;
        if(strName.length>5){
            var tempStr = strName.substr(0,5);
            strTempName = tempStr+"****@"+(accountsInfo[i].aName).split("@")[1];
        }else{
            strTempName = strName+"****@"+(accountsInfo[i].aName).split("@")[1];
        }
        checkbox.setAttribute("label", strTempName);
        newRow.appendChild(checkbox);
        var tmpSpacer = document.createElement("spacer");
        tmpSpacer.setAttribute("style", "width:25px");
        newRow.appendChild(tmpSpacer);
        var listbox = document.createElement("listbox");
        listbox.setAttribute("id", "tab_panel_row_listbox_"+index+"_"+accountsInfo[i].aId);
        listbox.setAttribute("style", "width:60px");
        //listbox.setAttribute("seltype", "cell");
        listbox.setAttribute("rows", "1");
        var listItem_pop3 = document.createElement("listitem");
        listItem_pop3.setAttribute("id", "tab_panel_row_listbox_listitempop3_"+index+"_"+accountsInfo[i].aId);
        listItem_pop3.setAttribute("value", "pop3");
        listItem_pop3.setAttribute("label", "POP3");
        var listItem_imap = document.createElement("listitem");
        listItem_imap.setAttribute("id", "tab_panel_row_listbox_listitemimap_"+index+"_"+accountsInfo[i].aId);
        listItem_imap.setAttribute("value", "imap");
        listItem_imap.setAttribute("label", "IMAP");
        if('pop3'===accountsInfo[i].aServiceType){
            listItem_pop3.setAttribute("selected", "true");
        }else{
            listItem_imap.setAttribute("selected", "true");
        }
        listbox.appendChild(listItem_pop3);
        listbox.appendChild(listItem_imap);
        newRow.appendChild(listbox);
        var tmpSpacer = document.createElement("spacer");
        tmpSpacer.setAttribute("style", "width:25px");
        newRow.appendChild(tmpSpacer);
        var menulist = document.createElement("menulist");
        menulist.setAttribute("id", "tab_panel_row_menulist_"+index+"_"+accountsInfo[i].aId);
        var menupopup = document.createElement("menupopup");
        menupopup.setAttribute("id", "tab_panel_row_menulist_menupopup_"+index+"_"+accountsInfo[i].aId);
        //menupopup.setAttribute("validate","never");
        menulist.appendChild(menupopup);
        var menuitem_remote = document.createElement("menuitem");
        var menuitem_local = document.createElement("menuitem");
        var menuitem_none = document.createElement("menuitem");
        var menuitem_close = document.createElement("menuitem");
        if(1 === accountsInfo[i].aLastStatus){
            menuitem_local.setAttribute("selected", "true");
   
        }else if(2 === accountsInfo[i].aLastStatus){
            menuitem_remote.setAttribute("selected", "true");
    
        }else if(0 === accountsInfo[i].aLastStatus){
            menuitem_none.setAttribute("selected", "true");
           
        }else if(3 === accountsInfo[i].aLastStatus){
            menuitem_close.setAttribute("selected", "true");
        }else{
            //alert("数据库中账户管理类型异常错误...");
             prompts.alert(null, "提示", "数据库中账户管理类型异常错误...");
            return;
        }
        menuitem_none.setAttribute("label", "选择模式");
        menupopup.appendChild(menuitem_none);
        menuitem_local.setAttribute("label", "本地管理");
        menupopup.appendChild(menuitem_local);
        menuitem_remote.setAttribute("label", "远程管理");
        menupopup.appendChild(menuitem_remote);
        /*
         * 
         * 账户如果处于远程控制模式将从账户从终端邮件目录中删除，并删除相关获取信息
         * 如果账户处于本地管理模式注销后，将不能执行同步，备份，上传下载等功能；但     
         * 本地配置的邮件账户不会消失；                           
         *                            
         */
        menuitem_close.setAttribute("label", "注销管理");
        menupopup.appendChild(menuitem_close);
        newRow.appendChild(menulist);
        rowheader.appendChild(newRow);
    }
    mainGrid.appendChild(rowheader);
    mainGroupBox.appendChild(mainGrid);
    var tmpSpacer = document.createElement("spacer");
    tmpSpacer.setAttribute("style","height:15px");
    mainGroupBox.appendChild(tmpSpacer);
    mainBox.appendChild(mainGroupBox);
    var mainHbox = document.createElement("hbox");
    mainHbox.setAttribute("align", "right");
    var btnCreate = document.createElement("button");
    btnCreate.setAttribute("id", "tab_panel_row_box_button_create_"+index);
    btnCreate.setAttribute("label", "提交");
    btnCreate.setAttribute("oncommand", "processCreateAccountRequest(event);");
//    btnCreate.onclick=function(){
//     var  idValue= selectedDeviceID; 
//     alert(idValue);
//     processCreateAccountRequest(event,idValue);   
//    };
    
    mainHbox.appendChild(btnCreate);

    mainBox.appendChild(mainHbox);

    curTabpanel.appendChild(mainBox);
        //alert("last");
}

/*加载账户信息，判断管理模式*/
function loadAccInfoPanel(panelID,name){
    //alert("index=");
     var selectedDeviceID;
        var statement = dDeviceSqlite.dbConnection.createStatement("\
                  SELECT dId FROM td_device where dName = :myVal");
    statement.params.myVal = name;
    try{
         while(statement.executeStep()){
             selectedDeviceID = statement.row.dId;
        }
    }
    finally{
        statement.reset();
    }
    var index=selectedDeviceID;  
    //var index = panelID.split("_")[2];
    //alert("index="+index);
    //alert("selectedDeviceID="+index);
    var curTabpanel = document.getElementById(panelID);
    
    var mainBox = document.createElement("vbox");
    mainBox.setAttribute("id","tabpanel_vbox_"+index);
    mainBox.setAttribute("flex","1");
    
    var tmpSpacer = document.createElement("spacer");
    tmpSpacer.setAttribute("style","height:15px");
    mainBox.appendChild(tmpSpacer);
    var headerBox = document.createElement("hbox");
    var tmpSpacer = document.createElement("spacer");
    tmpSpacer.setAttribute("style","width:25px");
    headerBox.appendChild(tmpSpacer);
    var strLabel = document.createElement("label");
    strLabel.setAttribute("value","当前设备内邮箱账户");
    headerBox.appendChild(strLabel);
    var tmpSpacer = document.createElement("spacer");
    tmpSpacer.setAttribute("style","width:50px");
    headerBox.appendChild(tmpSpacer);
    var strLabel = document.createElement("label");
    strLabel.setAttribute("value","服务类型");
    headerBox.appendChild(strLabel);
    var tmpSpacer = document.createElement("spacer");
    tmpSpacer.setAttribute("style","width:25px");
    headerBox.appendChild(tmpSpacer);
    var strLabel = document.createElement("label");
    strLabel.setAttribute("value","远程/本地管理");
    headerBox.appendChild(strLabel);
    mainBox.appendChild(headerBox);
    var mainGroupBox = document.createElement("groupbox");
    var tmpSpacer = document.createElement("spacer");
    tmpSpacer.setAttribute("style","height:15px");
    mainGroupBox.appendChild(tmpSpacer);
    var mainGrid = document.createElement("grid");
    mainGrid.setAttribute("maxheight","220px");
    mainGrid.setAttribute("minheight","220px");
    mainGrid.setAttribute("style","overflow:auto");
    var columnheader = document.createElement("columns");
    var column = document.createElement("column");
    column.setAttribute("flex", "3");
    columnheader.appendChild(column);
    var column = document.createElement("column");
    column.setAttribute("flex", "1");
    columnheader.appendChild(column);
    var column = document.createElement("column");
    column.setAttribute("flex", "1");
    columnheader.appendChild(column);
    var column = document.createElement("column");
    column.setAttribute("flex", "1");
    columnheader.appendChild(column);
    mainGrid.appendChild(columnheader);
    var rowheader = document.createElement("rows");
    var accountsInfo = [{aName:"账户名", 
                         aServiceType:"服务类型", 
                         aLocalStatus:"本地状态", 
                         aRemoteStatus:"远程状态",
                         aLastStatus:"最后状态",
                         aXml:"数据文件XML",
                         dId:0,
                         aId:0}];
    var statement = dDeviceSqlite.dbConnection.createStatement("\
                  SELECT * FROM td_account where dId = :myVal");
    statement.params.myVal = index;
    try{
         while(statement.executeStep()){
             accountsInfo.push({
                 aName:statement.row.aName, 
                 aServiceType:statement.row.aServiceType, 
                 aLocalStatus:statement.row.aLocalStatus, 
                 aRemoteStatus:statement.row.aRemoteStatus, 
                 aLastStatus:statement.row.aLastStatus,
                 aXml:statement.row.aXml,
                 dId:statement.row.dId,
                 aId:statement.row.aId});
        }
    }
    finally{
        //statement.finalize();
        statement.reset();
    }
    for(var i=1;i<accountsInfo.length;i++){
        var newRow = document.createElement("row");
        newRow.setAttribute("id", "tab_panel_row_"+index+"_"+accountsInfo[i].dId);
        var checkbox = document.createElement("checkbox");
        checkbox.setAttribute("id", "tab_panel_row_checkbox_"+index+"_"+accountsInfo[i].aId);
        var strName = (accountsInfo[i].aName).split("@")[0];
        var strTempName = null;
        if(strName.length>5){
            var tempStr = strName.substr(0,5);
            strTempName = tempStr+"****@"+(accountsInfo[i].aName).split("@")[1];
        }else{
            strTempName = strName+"****@"+(accountsInfo[i].aName).split("@")[1];
        }
        checkbox.setAttribute("label", strTempName);
        /**
         * 检测当前设备内账户的状态，设置显示情况
         */
        if(accountsInfo[i].aLastStatus!==0)
        {
          checkbox.setAttribute("checked",true);
        }
        
        //checkbox.setAttribute("checked",true);
        //checkbox.setAttribute("persist","checked");
        newRow.appendChild(checkbox);
        var tmpSpacer = document.createElement("spacer");
        tmpSpacer.setAttribute("style", "width:50px");
        newRow.appendChild(tmpSpacer);
        var listbox = document.createElement("listbox");
        listbox.setAttribute("id", "tab_panel_row_listbox_"+index+"_"+accountsInfo[i].aId);
        listbox.setAttribute("style", "width:65px");
        listbox.setAttribute("seltype", "cell");
        listbox.setAttribute("rows", "1");
        var listItem_pop3 = document.createElement("listitem");
        listItem_pop3.setAttribute("id", "tab_panel_row_listbox_listitempop3_"+index+"_"+accountsInfo[i].aId);
        listItem_pop3.setAttribute("value", "pop3");
        listItem_pop3.setAttribute("label", "POP3");
        var listItem_imap = document.createElement("listitem");
        listItem_imap.setAttribute("id", "tab_panel_row_listbox_listitemimap_"+index+"_"+accountsInfo[i].aId);
        listItem_imap.setAttribute("value", "imap");
        listItem_imap.setAttribute("label", "IMAP");
        if('pop3'===accountsInfo[i].aServiceType){
            listItem_pop3.setAttribute("selected", "true");
        }else{
            listItem_imap.setAttribute("selected", "true");
        }
        listbox.appendChild(listItem_pop3);
        listbox.appendChild(listItem_imap);
        newRow.appendChild(listbox);
        var tmpSpacer = document.createElement("spacer");
        tmpSpacer.setAttribute("style", "width:25px");
        newRow.appendChild(tmpSpacer);
        var menulist = document.createElement("menulist");
        menulist.setAttribute("id", "tab_panel_row_menulist_"+index+"_"+accountsInfo[i].aId);
        var menupopup = document.createElement("menupopup");
        menupopup.setAttribute("style","width:100px");
        menupopup.setAttribute("id", "tab_panel_row_menulist_menupopup_"+index+"_"+accountsInfo[i].aId);
        menulist.appendChild(menupopup);
        var menuitem_remote = document.createElement("menuitem");
        var menuitem_local = document.createElement("menuitem");
        var menuitem_none = document.createElement("menuitem");
        var menuitem_close = document.createElement("menuitem");
        if(1 === accountsInfo[i].aLastStatus){
            menuitem_local.setAttribute("selected", "true");
            menuitem_local.setAttribute("persist", "selected");
        }else if(2 === accountsInfo[i].aLastStatus){
            menuitem_remote.setAttribute("selected", "true");
            menuitem_remote.setAttribute("persist", "selected");
        }else if(0 === accountsInfo[i].aLastStatus){
            menuitem_none.setAttribute("selected", "true");
            menuitem_none.setAttribute("persist", "selected");
        }else if(3 === accountsInfo[i].aLastStatus){
            menuitem_close.setAttribute("selected", "true");
        }else{
            alert("数据库中账户管理类型异常错误...");
            return;
        }
        menuitem_none.setAttribute("label", "选择模式");
        menupopup.appendChild(menuitem_none);
        menuitem_local.setAttribute("label", "本地管理");
        menupopup.appendChild(menuitem_local);
        menuitem_remote.setAttribute("label", "远程管理");
        menupopup.appendChild(menuitem_remote);
        /*
         * 
         * 账户如果处于远程控制模式将从账户从终端邮件目录中删除，并删除相关获取信息
         * 如果账户处于本地管理模式注销后，将不能执行同步，备份，上传下载等功能；但     
         * 本地配置的邮件账户不会消失；                           
         *                            
         */
        menuitem_close.setAttribute("label", "注销管理");
        menupopup.appendChild(menuitem_close);
        newRow.appendChild(menulist);
        rowheader.appendChild(newRow);
    }
    mainGrid.appendChild(rowheader);
    mainGroupBox.appendChild(mainGrid);
    mainBox.appendChild(mainGroupBox);
    var tmpSpacer = document.createElement("spacer");
    tmpSpacer.setAttribute("style","height:15px");
    mainBox.appendChild(tmpSpacer);
    var mainHbox = document.createElement("hbox");
    mainHbox.setAttribute("align", "right");
    var btnCreate = document.createElement("button");
    btnCreate.setAttribute("id", "tab_panel_row_box_button_create_"+index);
    btnCreate.setAttribute("label", "提交");
    btnCreate.setAttribute("oncommand", "processCreateAccountRequest(event);");
//     btnCreate.onclick=function(){
//     var  idValue= selectedDeviceID;  
//     alert(idValue);
//     processCreateAccountRequest(event,idValue);   
//    };
    
    mainHbox.appendChild(btnCreate);

    mainBox.appendChild(mainHbox);

    curTabpanel.appendChild(mainBox);
}




function executeSelectStatus(elem_item_id){
    //alert("executeSelectStatus");
    var curDeviceListIndex = elem_item_id.split("_")[4];
    var curAccountListIndex = elem_item_id.split("_")[5];
    var serviceTypeItem = document.getElementById("tab_panel_row_listbox_"+curDeviceListIndex+"_"+curAccountListIndex);
    var serviceType = serviceTypeItem.selectedItem;    
    let curSelmenuListID = "tab_panel_row_menulist_"+curDeviceListIndex+"_"+curAccountListIndex;
    let curListItem = document.getElementById(curSelmenuListID);
    let curSelListItemIndex = curListItem.selectedIndex;
    switch(curSelListItemIndex){
        case 0:{
                //alert("请确定远程/本地管理行为...");
                prompts.alert(null, "提示", "请确定远程/本地管理行为...");
                return false;
        }
        case 1:{
                createAccountToLocal(curAccountListIndex, serviceType.value, 1);
                break;
        }
        case 2:{
                //alert('远程');
                createAccountToRemote(curAccountListIndex, serviceType.value, 2);
                sentsgetMsgHeadAction(curAccountListIndex,"Remote");
                break;
        }
        case 3:{
                closeAccountSyncPattern(curAccountListIndex, 0);
                sentsgetMsgHeadAction(curAccountListIndex,"Destroy");
                break;
        }
        default:
            break;
    }
    return true;
}

function createAccountToLocal(accountID, sStatus, aControlType){
    
    var statement = dDeviceSqlite.dbConnection.createStatement("UPDATE td_account \
                           SET aLocalStatus = :myStatus, aLastStatus = :myStatus,\
                           aControlType = 1,aServiceType = :myServiceType where aId = :myID");
    statement.params.myID          = accountID;
    statement.params.myStatus      = aControlType;
    statement.params.myServiceType = sStatus;
    try{
         while(statement.executeStep()){
             continue;
        }
    }
    finally{
        statement.reset();
    }
    statement = dDeviceSqlite.dbConnection.createStatement("SELECT aName, aPwd ,aServiceType FROM td_account WHERE aId = :myID");
    statement.params.myID = accountID;
    try{
         while(statement.executeStep()){
             gLocalAccountInfo.emailAddress = statement.row.aName;
             gLocalAccountInfo.userName = (statement.row.aName).split("@")[0];
             gLocalAccountInfo.passWord = statement.row.aPwd;
             gLocalAccountInfo.recvHostname="pop."+(statement.row.aName).split("@")[1];
             gLocalAccountInfo.sendHostname="smtp."+(statement.row.aName).split("@")[1];
             if((statement.row.aName).split("@")[1]=="163.com")
            {
                gLocalAccountInfo.recvPort="110";
                gLocalAccountInfo.socketType='3';
                gLocalAccountInfo.sendPort='25';
                
            }else if((statement.row.aName).split("@")[1]=="126.com"){
                
                gLocalAccountInfo.recvPort="110";
                gLocalAccountInfo.socketType='3';
                
            }else if((statement.row.aName).split("@")[1]=="qq.com")
            {
                gLocalAccountInfo.recvPort="995";
                gLocalAccountInfo.socketType='2';
                gLocalAccountInfo.sendPort='465';
                
            }else if((statement.row.aName).split("@")[1]=="sina.com"){
                
                gLocalAccountInfo.recvPort="110";
                gLocalAccountInfo.socketType='1';
                gLocalAccountInfo.sendPort='587';
                 
            }else if((statement.row.aName).split("@")[1]=="gmail.com"){
                gLocalAccountInfo.recvPort="995";
                gLocalAccountInfo.socketType='2';
                gLocalAccountInfo.sendPort='465';
            }else if((statement.row.aName).split("@")[1]=="nfs-hlj.com")
            {
                gLocalAccountInfo.recvPort="995";
                gLocalAccountInfo.socketType='2';
                gLocalAccountInfo.sendPort='465';
                gLocalAccountInfo.recvHostname="pop3.nfschina.com";
                gLocalAccountInfo.sendHostname="smtp.nfschina.com";
            }else{
                gLocalAccountInfo.recvPort="995";
                gLocalAccountInfo.socketType='2';
                gLocalAccountInfo.sendPort='465';
            }
        }
    }
    finally{
        statement.reset();
    }
    var config = new AccountConfig();
    
    checkIncomingServerAlreadyExists(config);
    config.rememberPassword = true;
    createAccountInBackend(config);
}

function createAccountToRemote(accountID, sStatus, ControlType){
    var statement = dDeviceSqlite.dbConnection.createStatement("UPDATE td_account \
                          SET aRemoteStatus = :myStatus, aLastStatus = :myStatus,\
                          aControlType = 1,aServiceType = :myServiceType where aId = :myID");
    statement.params.myID          = accountID;
    statement.params.myStatus      = ControlType;
    statement.params.myServiceType = sStatus;
    try{
         while(statement.executeStep()){
             continue;
        }
    }
    finally{
        statement.reset();
    }
    var menuItem = window.arguments[1];
    menuItem.setAttribute("checked",true);
    var panelTree = window.arguments[0];
    var elem_child = panelTree.childNodes;
    for(var i=0;i<elem_child.length;i++){
         if("showDevicesPanelTree" === elem_child[i].id){
             elem_child[i].parentNode.removeChild(elem_child[i]);
         }
//         if("hadTreeOrNewTree" === elem_child[i].id)
//         {
//             elem_child[i].parentNode.removeChild(elem_child[i]);
//         }
    }
    createDevicesListToPanel();
}

function closeAccountSyncPattern(accountID, aControlType){
    var statement = dDeviceSqlite.dbConnection.createStatement("\
                     UPDATE td_account SET aRemoteStatus = :myStatus, aLastStatus = 3,\
                     aControlType = 0 where aId = :myID");
    statement.params.myID      = accountID;
    statement.params.myStatus  = aControlType;
    try{
         while(statement.executeStep()){
             continue;
        }
    }
    finally{
        statement.reset();
    }
    var panelTree = window.arguments[0];
    var elem_child = panelTree.childNodes;
    for(var i=0;i<elem_child.length;i++){
         if("showDevicesPanelTree" === elem_child[i].id){
             elem_child[i].parentNode.removeChild(elem_child[i]);
         }
//         if("hadTreeOrNewTree" === elem_child[i].id)
//         {
//             elem_child[i].parentNode.removeChild(elem_child[i]);
//         }
    }
    createDevicesListToPanel();
}

function createDevicePanel(){
   if(window.arguments[0])
    {
      var panelTree = window.arguments[0];
    }else
    {

      var panelTree=document.getElementById('folderPaneBox');
    }

  /*添加tree间距移动变化*/
   /*添加tree间距移动变化*/
 if(window.opener)
  {
   let treeSp=window.opener.document.getElementById("hadTreeOrNewTree");
   if(treeSp===null)
   {
   var treeSplitter = document.createElement("splitter");
       treeSplitter.setAttribute("id", "hadTreeOrNewTree");
       treeSplitter.setAttribute("collapse", "before");
       panelTree.appendChild(treeSplitter);
   }
  }else{

  let treeSp=document.getElementById("hadTreeOrNewTree");
   if(treeSp===null)
   {
   var treeSplitter = document.createElement("splitter");
       treeSplitter.setAttribute("id", "hadTreeOrNewTree");
       treeSplitter.setAttribute("collapse", "before");
       panelTree.appendChild(treeSplitter);
   }
  }

  var newTreePanel = document.createElement("tree");
  newTreePanel.setAttribute("id", "showDevicesPanelTree");
  newTreePanel.setAttribute("class", "plain");
  newTreePanel.setAttribute("flex", "1");
  newTreePanel.setAttribute("hidecolumnpicker", "true");
  newTreePanel.setAttribute("persist", "mode");
  newTreePanel.setAttribute("mode", "all");
  newTreePanel.setAttribute("keepcurrentinview", "true");
  newTreePanel.setAttribute("context", "mobileDevicePaneContext");
  newTreePanel.setAttribute("disableKeyNavigation", "true");
  newTreePanel.setAttribute("onselect","DevicePaneSelectionHandle();");
  if(panelTree){
    var newTreeCols = document.createElement("treecols");
    newTreeCols.setAttribute("id", "firsttreecols");
    if(newTreeCols){
        var newTreecol = document.createElement("treecol");
        newTreecol.setAttribute("id", "firstcol");
        newTreecol.setAttribute("flex", "5");
        newTreecol.setAttribute("crop", "center");
        newTreecol.setAttribute("persist", "width");
        newTreecol.setAttribute("hideheader", "true");
        newTreecol.setAttribute("ignoreincolumnpicker", "true");
        newTreecol.setAttribute("primary", "true");
        newTreecol.setAttribute("sortActive", "true");
        newTreecol.setAttribute("sortDirection", "ascending");
        newTreeCols.appendChild(newTreecol);
      }
      newTreePanel.appendChild(newTreeCols);
  }
  panelTree.appendChild(newTreePanel);
  
  var newTreechildren = document.createElement("treechildren");
  if(newTreechildren){
      var newTreeitem = document.createElement("treeitem");
      newTreeitem.setAttribute("container", "true");
      newTreeitem.setAttribute("open", "true");
      if(newTreeitem){
          let newTreerow = document.createElement("treerow");
          let newTreecell = document.createElement("treecell");
          newTreecell.setAttribute("label", "终端邮件");
          newTreerow.appendChild(newTreecell); 
          newTreeitem.appendChild(newTreerow);
      }
      newTreechildren.appendChild(newTreeitem);
  }
  newTreePanel.appendChild(newTreechildren);
  return newTreeitem;
}
function searchOnlineDevice()
{
    var searchDevName=document.getElementById("serdev").value;
    if(searchDevName==="")
    {
        //alert("刷新列表")
        freshDevicesList();
    }
    else
    {
     //alert(searchDevName);
     var deviceInfo = [{id:0 ,status:0,handleStatus:0, name:"设备名", UDN:"设备描述码", listID:"dev_0"}];
     var sqlString="SELECT * FROM td_device where dName like "+"'%"+searchDevName+"%'";
     var statement = dDeviceSqlite.dbConnection.createStatement(sqlString);
     //statement.params.myVal = searchDevName;
     try{
         while(statement.executeStep()){
            deviceInfo.push(
                    {id:statement.row.dId,
                     status:statement.row.dStatus, 
                     handleStatus:statement.row.dHandleStatus,
                     name:statement.row.dName, 
                     UDN:statement.row.dUDN, 
                     listID:"dev_"+statement.row.dListId});
         }
    }
    finally{
        statement.reset();
    }
    
    deleteAllFindDeviceList();
    createFindDeviceList(deviceInfo);
    //alert("找到设备");
    }
    
    
}
function createDevicesListToPanel(){
    //alert(9);
  var Treeitem = createDevicePanel();
  //alert(1);
  var newTreechildren = document.createElement("treechildren");
 // alert(2);
  var devicesArr = getDevicesInfo();
  var devicesAccountsArr = getDeviceAccounts();
 // alert(3);
  for(i=0;i<devicesArr.length;i++){
    var newTreeitem = document.createElement("treeitem");
    newTreeitem.setAttribute("container", "true");
    newTreeitem.setAttribute("open", "true");
    newTreeitem.setAttribute("id", setDeviceID(devicesArr[i].dId));
    newTreeitem.setAttribute("statustext",setDeviceID(i));
    if(newTreeitem){
        var newTreerow = document.createElement("treerow");
        var newTreecell = document.createElement("treecell");
        newTreecell.setAttribute("src", "chrome://messenger/skin/icons/mobileIcon.png");
        newTreecell.setAttribute("label", devicesArr[i].dName);
        newTreerow.appendChild(newTreecell);
        newTreeitem.appendChild(newTreerow);
    } 
    var newTreechildrenAccount = document.createElement("treechildren");
    //alert(4);
    for(j=0;j<devicesAccountsArr[i].length;j++){
        var newTreeitemAccount = document.createElement("treeitem");
        newTreeitemAccount.setAttribute("container", "true");
        newTreeitemAccount.setAttribute("id", setDeviceAccountID(devicesArr[i].dId+"_"+devicesAccountsArr[i][j].aId));
        newTreeitemAccount.setAttribute("statustext", setDeviceAccountID(i+"_"+j));
        if(newTreeitemAccount){
            var newTreerowAccount = document.createElement("treerow");
            var newTreecellAccount = document.createElement("treecell");
            newTreecellAccount.setAttribute("src", "chrome://messenger/skin/icons/mailboxName.png");
            newTreecellAccount.setAttribute("label", devicesAccountsArr[i][j].aName);
            
            newTreerowAccount.appendChild(newTreecellAccount);
            newTreeitemAccount.appendChild(newTreerowAccount);
            
            var accountChild = document.createElement("treechildren");
            var accountItem = document.createElement("treeitem");
            accountItem.setAttribute("id", setDeviceAccountID(devicesArr[i].dId+"_"+devicesAccountsArr[i][j].aId+"_6"));
            accountItem.setAttribute("statustext", setDeviceAccountID(i+"_"+j+"send"));
            var accountRow = document.createElement("treerow");
            var accountCell = document.createElement("treecell");
            accountCell.setAttribute("src","chrome://messenger/skin/icons/sentImg.png");
            //accountCell.setAttribute("style",'image: url("chrome://messenger/skin/icons/folder-pane.png");-moz-image-region: rect(64px 16px 80px 0px);');
            accountCell.setAttribute("align","left");
            accountCell.setAttribute("label","发件箱");
            
            //accountCell.setAttribute("src","");
            accountRow.appendChild(accountCell);
            accountItem.appendChild(accountRow);
            accountChild.appendChild(accountItem);
            var accountItem = document.createElement("treeitem");
            accountItem.setAttribute("id", setDeviceAccountID(devicesArr[i].dId+"_"+devicesAccountsArr[i][j].aId+"_1"));
            accountItem.setAttribute("statustext", setDeviceAccountID(i+"_"+j+"recv"));
            var accountRow = document.createElement("treerow");
            var accountCell = document.createElement("treecell");
            accountCell.setAttribute("src","chrome://messenger/skin/icons/inboxImg.png");
            accountCell.setAttribute("align","left");
            accountCell.setAttribute("label", "收件箱");
            accountRow.appendChild(accountCell);
            accountItem.appendChild(accountRow);
            accountChild.appendChild(accountItem);
            var accountItem = document.createElement("treeitem");
            accountItem.setAttribute("id", setDeviceAccountID(devicesArr[i].dId+"_"+devicesAccountsArr[i][j].aId+"_3"));
            accountItem.setAttribute("statustext", setDeviceAccountID(i+"_"+j+"draft"));
            var accountRow = document.createElement("treerow");
            var accountCell = document.createElement("treecell");
            accountCell.setAttribute("src","chrome://messenger/skin/icons/drafshImg.png");
            accountCell.setAttribute("align","left");
            accountCell.setAttribute("label", "草稿箱");
            accountRow.appendChild(accountCell);
            accountItem.appendChild(accountRow);
            accountChild.appendChild(accountItem);
            newTreeitemAccount.appendChild(accountChild);
        } 
        newTreechildrenAccount.appendChild(newTreeitemAccount);
    }
    newTreeitem.appendChild(newTreechildrenAccount);
    
    newTreechildren.appendChild(newTreeitem);
  }
  Treeitem.appendChild(newTreechildren);
  //alert(5);
}

function setDeviceID(deviceName){
    let tmp = "Device_";
    return tmp+deviceName;
}

function setDeviceAccountID(deviceAccountName){
    let tmp = "Account_";
    return tmp+deviceAccountName;
}

function getDevicesInfo(){
    
    var comingDevices = new Array();
    
    while(dDeviceSqlite.initialized ===false || dDeviceSqlite.dbStatus===false){
        dDeviceSqlite.onLoad(); 
    }
    var statement = dDeviceSqlite.dbConnection.createStatement("\
              SELECT dId,dName FROM td_device WHERE dStatus = 2 ORDER BY dId ASC");
    try{
        while(statement.executeStep()){
            comingDevices.push({dId:statement.row.dId,
                    dName:statement.row.dName}); 
        }
    }
    finally{
        statement.reset();
    }
    return comingDevices;
}
/*menu专用*/
function getDevicesNameInfo(){
    
    var comingDevices = new Array();
    
    while(dDeviceSqlite.initialized ===false || dDeviceSqlite.dbStatus===false){
        dDeviceSqlite.onLoad(); 
    }
    var statement = dDeviceSqlite.dbConnection.createStatement("\
              SELECT dName FROM td_device WHERE dStatus = 2 ORDER BY dId ASC");
    try{
        while(statement.executeStep()){
            comingDevices.push(statement.row.dName); 
        }
    }
    finally{
        statement.reset();
    }
    return comingDevices;
}

function getDeviceAccounts(){
    var devicesCount = new Array();
    while(dDeviceSqlite.initialized ===false || dDeviceSqlite.dbStatus===false){
        dDeviceSqlite.onLoad(); 
    }
    var statement = dDeviceSqlite.dbConnection.createStatement("\
                            SELECT dId FROM td_device WHERE dStatus = 2");
    try{
        while(statement.executeStep()){
            devicesCount.push(statement.row.dId); 
        }
    }
    finally{
        statement.reset();
    }
 
    var comingDeviceAccounts = new Array();
    for(i=0;i<devicesCount.length;i++){
        comingDeviceAccounts[i] = new Array();
    }
    
    while(dDeviceSqlite.initialized ===false || dDeviceSqlite.dbStatus===false){
        dDeviceSqlite.onLoad(); 
    }
    var statement = dDeviceSqlite.dbConnection.createStatement("\
                SELECT td_device.dId,td_account.aId,td_account.aName FROM td_account \
                    LEFT JOIN td_device ON td_device.dId = td_account.dId \
                   WHERE td_account.aRemoteStatus = 2 ORDER BY td_device.dId ASC"); 
    try{
        var index = 0, tmp = 0;
        while(statement.executeStep()){
            if(0 == tmp){
                tmp = statement.row.dId;
                  comingDeviceAccounts[index].push({aId:statement.row.aId,
                    aName:statement.row.aName
                    });
            }else{
                if(tmp === statement.row.dId){
                    comingDeviceAccounts[index].push({aId:statement.row.aId,
                    aName:statement.row.aName
                    });
                }else{
                    tmp = statement.row.dId;
                    index++;
                    comingDeviceAccounts[index].push({aId:statement.row.aId,
                    aName:statement.row.aName
                    });
                }
            }
        }
    }
    finally{
        statement.reset();
    }   
    return comingDeviceAccounts;
}


/*menu专用*/
function getDeviceAccountsMenu(){
    var devicesCount = new Array();;
    while(dDeviceSqlite.initialized ===false || dDeviceSqlite.dbStatus===false){
        dDeviceSqlite.onLoad(); 
    }
    var statement = dDeviceSqlite.dbConnection.createStatement("\
                            SELECT dId FROM td_device WHERE dStatus = 2");
    try{
        while(statement.executeStep()){
            devicesCount.push(statement.row.dId); 
        }
    }
    finally{
        statement.reset();
    }
 
    var comingDeviceAccounts = new Array();
    for(i=0;i<devicesCount.length;i++){
        comingDeviceAccounts[i] = new Array();
    }
    
    while(dDeviceSqlite.initialized ===false || dDeviceSqlite.dbStatus===false){
        dDeviceSqlite.onLoad(); 
    }
    var statement = dDeviceSqlite.dbConnection.createStatement("\
     SELECT td_device.dId,td_account.aId,td_account.aName FROM td_account \
                    LEFT JOIN td_device ON td_device.dId = td_account.dId \
                   WHERE td_account.aRemoteStatus = 2 ORDER BY td_device.dId ASC"); 
    try{
        var index = 0, tmp = 0;
        while(statement.executeStep()){
            if(0 == tmp){
                tmp = statement.row.dId;
                comingDeviceAccounts[index].push(statement.row.aName);
            }else{
                if(tmp === statement.row.dId){
                    comingDeviceAccounts[index].push(statement.row.aName);
                }else{
                    tmp = statement.row.dId;
                    index++;
                    comingDeviceAccounts[index].push(statement.row.aName);
                }
            }
        }
    }
    finally{
        statement.reset();
    }   
    return comingDeviceAccounts;
}




function generationQRCode(tabpanelID, vCode){
    var curIndex = tabpanelID.split("_")[2];
    var curTabpanel = document.getElementById(tabpanelID);
    var qrBox = document.createElement("box");
    qrBox.setAttribute("id", "device_tab_qrbox_"+curIndex);
    var qrSpacer = document.createElement("space");
    qrSpacer.setAttribute("style", "height:10px");
    qrBox.appendChild(qrSpacer);
    var desLabel = document.createElementNS("http://www.w3.org/1999/xhtml","div");
    desLabel.setAttribute("style", "height:30px;font-size:16px;");
    desLabel.innerHTML = "扫描二维码或输入以下字符验证设备连接：";
    qrBox.appendChild(desLabel);
    var radioBox = document.createElementNS("http://www.w3.org/1999/xhtml","div");
    radioBox.setAttribute("style","display:none;");
    
    var divInfos = [   
        {id:"_1",value:"L",label:"7%"},
        {id:"_m",value:"M",label:"15%"},
        {id:"_q",value:"Q",label:"25%"},
        {id:"_h",value:"H",label:"30%"},
    ];
    for(var i=0;i<divInfos.length;i++){
        var inputName = document.createElementNS("http://www.w3.org/1999/xhtml","input");
        inputName.setAttribute("id","qr_capacity"+divInfos[i].id+"_"+curIndex);
        inputName.setAttribute("name","qr_capacity");
        inputName.setAttribute("type","radio");
        inputName.setAttribute("value",divInfos[i].value);
        radioBox.appendChild(inputName);
        var labelName = document.createElementNS("http://www.w3.org/1999/xhtml","label");
        labelName.setAttribute("for","qr_capacity"+divInfos[i].id+"_"+curIndex);
        labelName.innerHTML = divInfos[i].label;
        radioBox.appendChild(labelName);
    }
    qrBox.appendChild(radioBox);
    var qrSpacer = document.createElement("space");
    qrSpacer.setAttribute("style", "height:10px");
    qrBox.appendChild(qrSpacer);
    var qrContainer = document.createElementNS("http://www.w3.org/1999/xhtml","div");
    qrContainer.setAttribute("id", "qr_container_"+curIndex);
    qrContainer.setAttribute("style", "margin-left:130px;");
    qrBox.appendChild(qrContainer);
    var qrBr = document.createElementNS("http://www.w3.org/1999/xhtml","br");
    qrBox.appendChild(qrBr);
    
    var qrDivLabel = document.createElementNS("http://www.w3.org/1999/xhtml","div");
    
    var qrSpacer = document.createElement("space");
    qrSpacer.setAttribute("style", "width:155px;");
    qrDivLabel.appendChild(qrSpacer);
    var qrLabel = document.createElement("label");
    qrLabel.setAttribute("style", "font-size:18px;");
    qrLabel.setAttribute("value", "验证码："+vCode);
    qrDivLabel.appendChild(qrLabel);
    qrBox.appendChild(qrDivLabel);
    curTabpanel.appendChild(qrBox);
    
    var qr_coder = null;
    var container = document.getElementById(qrContainer.id);
    var jqContainer = $(container);
    qr_coder = new QRCoder(jqContainer);
    qr_coder.setMode(1);
    qr_coder.draw(vCode,"H",'icon.png',function(data){});
}

function finishSelTabpanelContent(dev){
    
    var deviceTabs = document.getElementById("device_tabs");

    var elem_child = deviceTabs.childNodes;
       // alert("deviceTabs ="+deviceTabs);
  
    var curTabPanel = null;
    for(var i=0;i<elem_child.length;i++){
        if("tab" === elem_child[i].nodeName){
            if(true === elem_child[i].selected && "首页" !== elem_child[i].label){
                //alert("elem_child.length ="+elem_child.length);
                curTabPanel = document.getElementById(elem_child[i].value);
            }
        }
    }
    if(curTabPanel){
        var childs = curTabPanel.childNodes;
        for(var i=0;i<childs.length;i++){
            if("vbox" === childs[i].nodeName){
                return;
            }
        }
        for(var i=childs.length-1;i>=0;i--){
            curTabPanel.removeChild(childs.item(i));
        }
    }
    var statement = dDeviceSqlite.dbConnection.createStatement("\
                  UPDATE td_device SET dStatus = 2, dHandleStatus = 1 where dListId = :myVal");
    statement.params.myVal =curTabPanel.id.split("_")[2];
    try{
         while(statement.executeStep()){
            //statement.finalize();
            continue;
        }
    }
    finally{
        statement.reset();
    }
     //alert(812345);
    //statement.finalize();
    freshDevicesList();
     //alert(12345);
    saveAccountsInfoToDB(curTabPanel.id,dev);
     //alert(2345);
     //alert("pnaleid="+curTabPanel.id);
    createCurTabPanel(curTabPanel.id,dev);
    /*连接成功后更新邮件树*/
    if(window.arguments[0])
    {   
     var panelTree =  window.arguments[0];
    }else{
        
     var panelTree =  document.getElementById('folderPaneBox');    
    }
     if(panelTree)
     {    
         var elem_child = panelTree.childNodes;
         for(var i=0;i<elem_child.length;i++){
            if("showDevicesPanelTree" === elem_child[i].id){
                  elem_child[i].parentNode.removeChild(elem_child[i]);
            }
         }
         createDevicesListToPanel();
     }    
     //alert(345);
}
function openLinkDevAccout(linkedobj)
{
    //alert(111111);
    var list = document.getElementById('thelist');
    var item = list.selectedItems[0];
    var name=null;
    var id=null; 
    //alert(item.childNodes[1].getAttribute("label"));
    for(var i=0;i<linkedobj.length;i++)
    {
        let getLinkedObj=linkedobj[i];
        if(item.childNodes[1].getAttribute("label")===getLinkedObj.onetabname)
        {
             name=getLinkedObj.onetabname;
             id=getLinkedObj.listoneid;
             udn=getLinkedObj.devUDN;
             //alert("name="+name+"id="+id);
        }
    }
    createLinkedDevPanel(name,id,udn);
    var deviceTabs = document.getElementById("device_tabs");
    var elem_child = deviceTabs.childNodes;
    
     //alert(elem_child.length);   
    var curTabPanel = null;
    for(var i=0;i<elem_child.length;i++){
        if("tab" === elem_child[i].nodeName){
            if(name=== elem_child[i].label){
                //alert("elem_child.label ="+elem_child[i].label);
                curTabPanel = document.getElementById(elem_child[i].value);
            }
            
        }
    }
    if(curTabPanel){
        var childs = curTabPanel.childNodes;
        for(var i=0;i<childs.length;i++){
            if("vbox" === childs[i].nodeName){
                return;
            }
        }
        for(var i=childs.length-1;i>=0;i--){
            curTabPanel.removeChild(childs.item(i));
        }
    }
    //alert(55555);
    //alert("id="+curTabPanel.id);
    loadAccInfoPanel(curTabPanel.id,name); 
    //alert(22222);
}
function createLinkedDevPanel(name,id,udn)
{
    var deviceTabs = document.getElementById("device_tabs");
    var deviceTabpanels = document.getElementById("device_tabpanels");
    var elem_child = deviceTabs.childNodes;
    var num=deviceTabpanels.childNodes.length;
//    var elem_child_panels=deviceTabpanels.childNodes;
//    for(var i=1;i<elem_child.length;i++)
//    {
//        deviceTabs.removeChild(elem_child[i]);
//        deviceTabpanels.removeChild(elem_child_panels[i]);
//    }
//true === elem_child[i].selected &&
    //alert("传入的值="+name);
    for(var i=0;i<elem_child.length;i++){
        if("tab" === elem_child[i].nodeName){
            if(name !== elem_child[i].label){
                //alert("elem_child.name ="+elem_child[i].label);
                continue;
            }
            else
            {
                //alert("返回");
                return;
            }
        }
    }
    var newTab = document.createElement("tab");
        newTab.setAttribute("id", "device_tab_"+id);
        newTab.setAttribute("label",name);//selectedDeviceInfo[i].dName
        newTab.setAttribute("crop", "end");
        newTab.setAttribute("style", "width:80px");
        newTab.setAttribute("value", "device_tabpanel_"+id);
        newTab.setAttribute("linkedpanel", "device_tabpanel_"+id);
        deviceTabs.appendChild(newTab);
        var tabbox=document.getElementById("myTabList");
        tabbox.selectedTab=newTab;
        var newTabpanel = document.createElement("tabpanel");
        newTabpanel.setAttribute("minheight","330");
        newTabpanel.setAttribute("manheight","330");
        newTabpanel.setAttribute("id","device_tabpanel_"+id);
        newTabpanel.setAttribute("label",udn);
        deviceTabpanels.setAttribute("selectedIndex",num);   
        deviceTabpanels.appendChild(newTabpanel);
        
}






 var gLocalAccountInfo = {
        realName:"email1",
        emailAddress:"邮箱地址",
        type:"pop3",
        recvHostname:"pop3.163.com",
        recvPort:"110",
        sendHostname:"smtp.163.com",
        sendPort:"25",
        userName:"邮箱名称",
        passWord:"邮箱密码",
        socketType:3,
        auth:3,
        source:1
};

function AccountConfig()
{
  this.incoming = this.createNewIncoming();
  this.incomingAlternatives = [];
  this.outgoing = this.createNewOutgoing();
  this.outgoingAlternatives = [];
  this.identity =
  {
    realname : gLocalAccountInfo.realName,
    emailAddress : gLocalAccountInfo.emailAddress,
  };
  this.inputFields = [];
  this.domains = [];
};
AccountConfig.prototype =
{
  incoming : null,
  outgoing : null,
  incomingAlternatives : null,
  outgoingAlternatives : null,
  id : null,
  source : gLocalAccountInfo.source,
  displayName : null,
  inputFields : null,
  domains : null,
  createNewIncoming : function()
  {
    return {
      type : gLocalAccountInfo.type,
      hostname : gLocalAccountInfo.recvHostname,
      port : gLocalAccountInfo.recvPort,
      username : gLocalAccountInfo.userName,
      password : gLocalAccountInfo.passWord,
      socketType : gLocalAccountInfo.socketType,
      badCert : false,
      auth : gLocalAccountInfo.auth,
      authAlternatives : null,
      checkInterval : 10,
      loginAtStartup : true,
      useGlobalInbox : false,
      leaveMessagesOnServer : true,
      daysToLeaveMessagesOnServer : 14,
      deleteByAgeFromServer : true,
      deleteOnServerWhenLocalDelete : true,
      downloadOnBiff : true,
    };
  },
  createNewOutgoing : function()
  {
    return {
      type : "smtp",
      hostname : gLocalAccountInfo.sendHostname,
      port : gLocalAccountInfo.sendPort, 
      username : gLocalAccountInfo.userName, 
      password : gLocalAccountInfo.passWord, 
      socketType : gLocalAccountInfo.socketType, 
      badCert : false, 
      auth : gLocalAccountInfo.auth, 
      authAlternatives : null, 
      addThisServer : true,
      useGlobalPreferredServer : false,
      existingServerKey : null,
      existingServerLabel : null,
    };
  },
  copy : function()
  {
    var result = new AccountConfig();
    for (var prop in this)
      result[prop] = deepCopy(this[prop]);

    return result;
  },
  isComplete : function()
  {
    return (!!this.incoming.hostname && !!this.incoming.port &&
         !!this.incoming.socketType && !!this.incoming.auth &&
         !!this.incoming.username &&
         (!!this.outgoing.existingServerKey ||
          (!!this.outgoing.hostname && !!this.outgoing.port &&
           !!this.outgoing.socketType && !!this.outgoing.auth &&
           !!this.outgoing.username)));
  },
};



/*获取邮件头信息*/
function sentsgetMsgHeadAction(id,managerMode)
{
    var locationStr=null;
    var xmlFile=null;
    var dIdNum=null;
    var devName=null;
    var gEN = Components.classes["@nfs.hlj/upnpservice;1"].createInstance(Components.interfaces.nsIUpnpService);
    var statement = dDeviceSqlite.dbConnection.createStatement("\
                  SELECT aXml,dId FROM td_account where aId = :myVal");
                  statement.params.myVal = id;
                 
        try {
                 while (statement.executeStep()) {
                      xmlFile = statement.row.aXml;
                      dIdNum = statement.row.dId;
                      }
                   }
                 
        finally {
                  statement.reset();
                }
    var statement = dDeviceSqlite.dbConnection.createStatement("\
                  SELECT dLocation,dName FROM td_device where dId = :myVal");
                  statement.params.myVal = dIdNum;
                 
        try {
                 while (statement.executeStep()) {
                      locationStr = statement.row.dLocation;
                      devName = statement.row.dName;
                      }
                   }
                 
        finally {
                  statement.reset();
                }            
      
    var httpHead = locationStr.split("/")[0];
    var ipAndPort = locationStr.split("/")[2];
    var serviceSubStr =httpHead+"\/\/"+ipAndPort+"/upnp/control/tvcontrol1";
    //alert(serviceSubStr);
    //gEN.SendAction(serviceSubStr,"GetAllEmail",xmlFile,managerMode);
    if(managerMode==="Remote")
    {     
      gEN.SendAction(serviceSubStr,"GetAllEmail",xmlFile,managerMode);  
      //parserLocalFile("3da2027a-6ec2-4b81-a8c5-ad811a5763a6_message.xml",devName);
      //"3da2027a-6ec2-4b81-a8c5-ad811a5763a6_message.xml"
      //setTimeout(function () {
      //        var dn=devName;
      //        var fn=xmlFile;        
      //        checksDownLoadResult(fn,dn);
    //    },300);
    }else if(managerMode==="Destroy")
    {
//        /*删除该账户内的邮件头信息*/
//        var statement = dDeviceSqlite.dbConnection.createStatement("\
//                  DELETE FROM td_email WHERE eName = :myVal and dId =:myVal1");
//                  statement.params.myVal = xmlFile.split("_")[0];
//                  statement.params.myVal1 = dIdNum;
//            try{
//                 statement.executeStep();
//            }
//            finally{
//                statement.reset();
//            }
      gEN.SendAction(serviceSubStr,"GetAllEmail",xmlFile,managerMode);
      Components.utils.import("resource://gre/modules/FileUtils.jsm");
    //Components.utils.import("resource://gre/modules/NetUtil.jsm");     
    var filetmp = FileUtils.getFile("ProfD", [xmlFile]);
    if(filetmp.exists())
    {
        filetmp.remove(true);
    }else{
        return;
    }
    }
                    
    }
        
/*检测邮件头信息是否下载成功*/
function checksDownLoadResult(fileName,devName)
{
     var gEN = Components.classes["@nfs.hlj/upnpservice;1"].createInstance(Components.interfaces.nsIUpnpService);
  
    var flagnow=gEN.actionValue;
    if(flagnow==="success")
    {
       
        clearTimeout(timeSwitch);
         parserLocalFile(fileName,devName);
    }
    else
    { 
        var timeSwitch=setTimeout(function () {
        var dn=devName;
        var fn=fileName; 
        checkDownLoadResult(fn,dn);
    },300);
    }   
}
/*获取远程连接设备中的通讯录信息*/
function sentsgetContactsAction(deviceid)
{
    
    var locationStr=null;
    var xmlFile=null;
    var dIdNum=null;
    var linkdevName=null;
    var id = deviceid.split("_")[5];
    var gEN = Components.classes["@nfs.hlj/upnpservice;1"].createInstance(Components.interfaces.nsIUpnpService);
    var statement = dDeviceSqlite.dbConnection.createStatement("\
                  SELECT dId FROM td_account where aId = :myVal");
                  statement.params.myVal = id;
                 
        try {
                 while (statement.executeStep()) {
                      //xmlFile = statement.row.aXml;
                      dIdNum = statement.row.dId;
                      }
                   }
                 
        finally {
                  statement.reset();
                }
    var statement = dDeviceSqlite.dbConnection.createStatement("\
                  SELECT dLocation,dName FROM td_device where dId = :myVal");
                  statement.params.myVal = dIdNum;
                  
        try {
                 while (statement.executeStep()) {
                      locationStr = statement.row.dLocation;
                      linkdevName=statement.row.dName;
                      }
                   }
                 
        finally {
                  statement.reset();
                }            
      
    var httpHead = locationStr.split("/")[0];
    var ipAndPort = locationStr.split("/")[2];
    var serviceSubStr=httpHead+"\/\/"+ipAndPort+"/contacts/contacts.xml";
    
     var dirService = Components.classes["@mozilla.org/file/directory_service;1"].
    getService(Components.interfaces.nsIProperties);
    var dir = dirService.get("ProfD", Components.interfaces.nsIFile);
    var pathS = dir.path;
    var pathc="../../../.."+pathS;
    //var pathc=gEN.path;
    var lpath=pathc+"/contacts.xml";
    /*本地测试时可先注释，建立远程连接后，取消注释*/
    gEN.downfile(serviceSubStr,lpath);//GetAppMail,AccName,MessageId; 
    //testjinhai(); 
    //alert(1);
    parserLocalFile("contacts.xml",linkdevName);
  
}

/*邮件夹同步*/
function syncMailFolder(deviceName,accountName,mode)
{
//    alert(mode);
//    alert(deviceName);
//    alert(accountName);
   // var xmlFile =  accountName.split("_")[0] + "_" + mode + "_modify.xml"; 
    var statement = dDeviceSqlite.dbConnection.createStatement("\
                     SELECT dId,dLocation FROM td_device WHERE dName = :myVal");
    statement.params.myVal = deviceName;  
    var deviceId = null;
    var location = null;
    try
    {
        while(statement.executeStep())
        {
            deviceId = statement.row.dId;
            location = statement.row.dLocation;
            continue;
        }
    }
    finally
    {
        statement.reset();
    }
   // alert(location);
    statement = dDeviceSqlite.dbConnection.createStatement("\
                     SELECT aXml,aName FROM td_account WHERE dId = :myVal");
    statement.params.myVal =deviceId;
    var accountXml = null;
    var aName = null;
     try{
         while(statement.executeStep())
         {
            aName = statement.row.aName;
            if(aName === accountName)
            {
                accountXml = statement.row.aXml;
            }
            continue;
        }
    }
    finally
    {
        statement.reset();
    }
    var httpHead = location.split("/")[0];
    var ipAndPort = location.split("/")[2];
    var serviceSubStr=httpHead+"\/\/"+ipAndPort+"/upnp/control/tvcontrol1";
    var accountUuid = accountXml.split(".")[0];
    //alert(accountUuid); 
    gEN.SendAction(serviceSubStr,"SyncRequest",accountUuid,mode);
    var nbox=document.getElementById("syncinfonotify");
    var onenotify= nbox.getNotificationWithValue(accountName);
    if(onenotify)
    {    
      nbox.removeNotification(onenotify);
      prompts.alert(null, "同步邮件", "终端邮件数据同步成功");
    }else{
      return;      
    }  
   //alert("sync over");
   //parserSyncLocalFile("dc4aa355-3d9f-48fd-8734-eab039bb3f51_recv_modify.xml","xx");
//   var fileName = accountXml.split("_")[0] + "_" + mode + "_modify.xml";
//   parserSyncLocalFile(fileName,deviceName,accountName);
//    setTimeout(function () {
//        var dn=fileName;
//        var fn=deviceName;
//        var an=accountName;
//        checkSyncOprResult(fn,dn,an);
//    },300);
}
/*检测同步邮件头信息是否下载成功*/
var timeSwitch=null
function checkSyncOprResult(fileName,devName,accName)
{
     var gEN = Components.classes["@nfs.hlj/upnpservice;1"].createInstance(Components.interfaces.nsIUpnpService);
  
    var flagnow=gEN.actionValue;
      //alert("flagnow="+flagnow);
    if(flagnow==="success")//
    {
        //alert("定时开关");
         clearTimeout(timeSwitch);
         parserSyncLocalFile(fileName,devName,accName);
        //gEN.actionValue="error";
    }
    else
    { 
        timeSwitch=setTimeout(function () {
        var dn=devName;
        var fn=fileName; 
        var an=accName;
        //alert("1A="+dn+"2A="+fn);
        checkDownLoadResult(fn,dn,an);
    },300);
    }   
}
